package com.wb.auth;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import com.haohope.framework.util.HttpUtil;
import com.wb.common.XwlBuffer;
import com.wb.util.WebUtil;

public class ButtonAuth {
	private static JSONObject getXwl(String url) throws Exception {
		//m?xwl=sys/tool/ggg
		if(StringUtils.isEmpty(url)) {
			return null;
		}
		if(!url.endsWith(".xwl"))url += ".xwl";
		if(url.startsWith("m?xwl=")) {
			return XwlBuffer.get(url.replace("m?xwl=", ""));
		}else {
			return XwlBuffer.get(url);
		}
	}
	private static boolean hasAuth(HttpServletRequest request,String url) {
		String myroles = (String) request.getSession().getAttribute("sys.roleList");
		try {
			JSONObject json = getXwl(url);
			if(null==json)return false;
			Boolean loginRequired = json.getBoolean("loginRequired");
			if(!loginRequired) {
				return true;
			}
			if(StringUtils.isEmpty(myroles)) {
				return false;
	    	}
			JSONObject roles = json.getJSONObject("roles");
    		for(String myrole:myroles.split(",")) {
    			if(null != roles.get(myrole)) {
    				return true;
    			}
    		}
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return false;
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void isHidden(HttpServletRequest request, HttpServletResponse response) throws IOException {
		JSONObject result = new JSONObject();
		Set<String> urls = 
				(Set<String>) ((List) HttpUtil.createPostParams(request, List.class)).stream().map(i->i.toString()).collect(Collectors.toSet());
	    for(String url:urls) {
	    	result.put(url, hasAuth(request,url));
	    }
	    WebUtil.send(response, result);
	}
	
}
